﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Web.Mvc;
using Enyim.Caching;
using SilenthinkContract;
using System.Web.Helpers;
using SilenthinkCommon.Extension;

namespace Web.Areas.My.Controllers
{
    public class HomeController : MyBaseController
    {
        public HomeController(IBaseService baseService, IStoreService storeService, IPassportService passportService, IOrderService orderService, IExtraService extraService, IMemcachedClient cache)
            : base(baseService, storeService, passportService, orderService, extraService, cache)
        {
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Address()
        {
            var identity = User.Identity.GetIdentity();
            var model = PassportService.GetUserAddress(identity.Id);
            return View(model);
        }
        public ActionResult Avatar()
        {
            return PartialView();
        }
        [HttpPost]
        public string Avatar(string imageSource, float imageH, float imageW, float imageRotate, float imageX, float imageY, float selectorH, float selectorW, float selectorX, float selectorY, float viewPortH, float viewPortW)
        {
            //To Values
            var pWidth = imageW;
            var pHeight = imageH;
            var angle = imageRotate;
            var img = Image.FromFile(Server.MapPath(imageSource));
            //Original Values
            var width = img.Width;
            var height = img.Height;

            //Resize
            var imageP = ResizeImage(img, (int)pWidth, (int)pHeight);

            var widthR = imageP.Width;
            var heightR = imageP.Height;
            //Rotate if angle is not 0.00 or 360
            if (angle > 0.0F && angle < 360.00F)
            {
                imageP = RotateImage(imageP, angle);
                pWidth = imageP.Width;
                pHeight = imageP.Height;
            }

            //Calculate Coords of the Image into the ViewPort
            float srcX;
            float dstX;
            float srcY;
            float dstY;

            if (pWidth > viewPortW)
            {
                srcX = Math.Abs(imageX - Math.Abs((imageW - pWidth) / 2));
                dstX = 0;
            }
            else
            {
                srcX = 0;
                dstX = imageX + ((imageW - pWidth) / 2);
            }
            if (pHeight > viewPortH)
            {
                srcY = Math.Abs(imageY - Math.Abs((imageH - pHeight) / 2));
                dstY = 0;
            }
            else
            {
                srcY = 0;
                dstY = imageY + ((imageH - pHeight) / 2);
            }


            //Get Image viewed into the ViewPort
            imageP = ImageCopy(imageP, dstX, dstY, srcX, srcY, viewPortW, viewPortH, pWidth, pHeight);
            //image_p.Save(context.Server.MapPath("test_viewport.jpg"));
            //Get Selector Portion
            imageP = ImageCopy(imageP, 0, 0, selectorX, selectorY, selectorW, selectorH, viewPortW, viewPortH);
            var fileName = String.Format("/test{0}.jpg", DateTime.Now.Ticks.ToString());
            imageP.Save(Server.MapPath(fileName));


            imageP.Dispose();
            img.Dispose();
            //imgSelector.Dispose();
            return fileName;
        }
        private static Bitmap ImageCopy(Image srcBitmap, float dstX, float dstY, float srcX, float srcY, float dstWidth, float dstHeight, float srcWidth, float srcHeight)
        {
            // Create the new bitmap and associated graphics object
            var sourceRec = new RectangleF(srcX, srcY, dstWidth, dstHeight);
            var destRec = new RectangleF(dstX, dstY, dstWidth, dstHeight);
            var bmp = new Bitmap(Convert.ToInt32(dstWidth), Convert.ToInt32(dstHeight));
            var g = Graphics.FromImage(bmp);
            // Draw the specified section of the source bitmap to the new one
            g.DrawImage(srcBitmap, destRec, sourceRec, GraphicsUnit.Pixel);
            // Clean up
            g.Dispose();

            // Return the bitmap
            return bmp;

        }


        private Image ResizeImage(Image img, int width, int height)
        {
            Image.GetThumbnailImageAbort callback = GetThumbAbort;
            return img.GetThumbnailImage(width, height, callback, IntPtr.Zero);

        }

        public bool GetThumbAbort()
        {
            return false;
        }

        /// <summary>
        /// method to rotate an image either clockwise or counter-clockwise
        /// </summary>
        /// <param name="img">the image to be rotated</param>
        /// <param name="rotationAngle">the angle (in degrees).
        /// NOTE: 
        /// Positive values will rotate clockwise
        /// negative values will rotate counter-clockwise
        /// </param>
        /// <returns></returns>
        private static Image RotateImage(Image img, double rotationAngle)
        {
            if (img == null) throw new ArgumentNullException("img");
            //create an empty Bitmap image
            var bmp = new Bitmap(img.Width, img.Height);

            //turn the Bitmap into a Graphics object
            var gfx = Graphics.FromImage(bmp);

            //now we set the rotation point to the center of our image
            gfx.TranslateTransform(bmp.Width / 2f, bmp.Height / 2f);

            //now rotate the image
            gfx.RotateTransform((float)rotationAngle);

            gfx.TranslateTransform(-bmp.Width / 2f, -bmp.Height / 2f);

            //set the InterpolationMode to HighQualityBicubic so to ensure a high
            //quality image once it is transformed to the specified size
            gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;

            //now draw our new image onto the graphics object
            gfx.DrawImage(img, new Point(0, 0));

            //dispose of our Graphics object
            gfx.Dispose();

            //return the image
            return bmp;
        }
    }
}
